package club.gskj.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GuliFeignConfig {

    /**
     * 添加Feign调用拦截器，每次调用服务之前，将老请求中的请求头信息同步到 新请求中。方便在其他服务中可以直接通过cookie获取登录用户信息
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                // 获取老的请求的所有信息
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    // 获取老的请求对象，调用远程服务时的请求对象
                    HttpServletRequest request = requestAttributes.getRequest();

                    // 获取请求中 Cookie信息
                    String oldCookie = request.getHeader("Cookie");

                    // 同步老的请求头信息到新请求对象template中
                    template.header("Cookie", oldCookie);
                }
            }
        };
    }
}
